package top.yxqz.filter.demo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr.余
 * @date 2022/12/6
 * @package top.yxqz.filter.demo
 * 评论的拦截器
 */
@WebFilter(value = "/comment",initParams = {@WebInitParam(name = "zh",value = "gg")})
public class CommentFilter implements Filter {

    private  FilterConfig config ;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        config  = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        得到用户输入的数据
        HttpServletRequest request  = (HttpServletRequest) servletRequest;
        HttpServletResponse response   = (HttpServletResponse) servletResponse;
        response.setContentType("text/html;charset=utf-8");
        String comment = request.getParameter("comment"); //前端传来的数据
        String zh = config.getInitParameter("zh"); //得到脏话（要拦截的词语）
//        操作
        if (comment.contains(zh)){
            comment = comment.replace(zh, "**");
        }
//        丢数据（修改数据）
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("comment",comment);
//        放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
